package com.zbar.lib;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.auto.learning.R;
import com.auto.learning.activity.BaseActivity;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.UserInfoBean;
import com.auto.learning.event.BindSuccessEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.tools.AES;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.view.SharedPreferencesUtils;
import com.zbar.lib.camera.CameraManager;
import com.zbar.lib.decode.CaptureActivityHandler;
import com.zbar.lib.decode.InactivityTimer;

/**
 *
 * 描述: 扫描界面
 */
@SuppressLint("UseCheckPermission")
public class CaptureActivity extends BaseActivity implements Callback {

	private CaptureActivityHandler handler;
	private boolean hasSurface;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.50f;
	private boolean vibrate;
	private int x = 0;
	private int y = 0;
	private int cropWidth = 0;
	private int cropHeight = 0;
	private int month;
	private RelativeLayout mContainer = null;
	private RelativeLayout mCropLayout = null;
	private boolean isNeedCapture = false;
	private boolean isHand;// 是否手动
	private boolean isNeedRefreshUi = false;
	private Handle mHandler = new Handle(this) {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				try {
					ResponeResult responeResult = (ResponeResult) msg.obj;
					if (responeResult != null) {
						CommonMethod.makeNotice(CaptureActivity.this, "绑定成功，快去读书吧");
						JSONObject jsonObject = new JSONObject(responeResult.getData());
						String companyName = jsonObject.getString("companyName");
						String code = jsonObject.getString("code");
						SharedPreferencesUtils.setParam(CaptureActivity.this, "companyCode_" + SharedPreferencesUtils.getParam(CaptureActivity.this, HttpRequestHelper.USERID, 0), code);
						MyUserInfo.getInstance().getUserInfoBean().setCompanyName(companyName);
						EventBus.getEventBus("bind_success_refresh").post(new BindSuccessEvent(207));
						setResult(212);
						finish();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case HttpRequestHelper.GETDATA_FAIL:
				Message _msg = new Message();
				_msg.what = R.id.restart_preview;
				handler.sendMessageDelayed(_msg, 3000);
				CommonMethod.makeNotice(CaptureActivity.this, msg.obj.toString());
				break;
			
			case 0x100:
//				showHint("关注企业成功，您将获得" + month + "个月包月体验", 0x102);
//				SharePreHelper.setNeedMainRefresh(CaptureActivity.this, true);
				break;
			case 0x101:
				isHand = false;
//				CommonMethod.makeNotice(CaptureActivity.this, msg.obj.toString());
//				handler.sendEmptyMessage(0x103);
				showHint(msg.obj.toString(), 0x103);
				break;
			case 0x102:
				CaptureActivity.this.finish();
				break;
			case 0x103:
				handler.sendEmptyMessage(R.id.restart_preview);
				break;
			}
		};
	};

	public boolean isNeedCapture() {
		return isNeedCapture;
	}

	public void setNeedCapture(boolean isNeedCapture) {
		this.isNeedCapture = isNeedCapture;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getCropWidth() {
		return cropWidth;
	}

	public void setCropWidth(int cropWidth) {
		this.cropWidth = cropWidth;
	}

	public int getCropHeight() {
		return cropHeight;
	}

	public void setCropHeight(int cropHeight) {
		this.cropHeight = cropHeight;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_qr_scan);
		setTitle("扫一扫");
//		setMoreBtn("手动");
		/*baseMore.setOnClickListener(new android.view.View.OnClickListener() {

			@Override
			public void onClick(View v) {
				isHand = true;
				showDialog();
			}
		});*/
		// 初始化 CameraManager
		CameraManager.init(getApplication());
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);

		mContainer = (RelativeLayout) findViewById(R.id.capture_containter);
		mCropLayout = (RelativeLayout) findViewById(R.id.capture_crop_layout);

		ImageView mQrLineView = (ImageView) findViewById(R.id.capture_scan_line);
		TranslateAnimation mAnimation = new TranslateAnimation(
				TranslateAnimation.ABSOLUTE, 0f, TranslateAnimation.ABSOLUTE,
				0f, TranslateAnimation.RELATIVE_TO_PARENT, 0f,
				TranslateAnimation.RELATIVE_TO_PARENT, 0.9f);
		mAnimation.setDuration(1500);
		mAnimation.setRepeatCount(-1);
		mAnimation.setRepeatMode(Animation.REVERSE);
		mAnimation.setInterpolator(new LinearInterpolator());
		mQrLineView.setAnimation(mAnimation);
//		Log.d("CaptureActivity", AES.encrypt("zhdt01"));
	}

	boolean flag = true;

	protected void light() {
		if (flag == true) {
			flag = false;
			// 开闪光灯
			CameraManager.get().openLight();
		} else {
			flag = true;
			// 关闪光灯
			CameraManager.get().offLight();
		}

	}

	/**
	 * 手动输入对话框
	 */
	private void showDialog() {
		final EditText et = new EditText(this);
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("请输入二维码").setIcon(android.R.drawable.ic_dialog_info)
				.setView(et);
		builder.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				QrCodeThd(et.getText().toString());
				dialog.dismiss();
			}

		});
		builder.setNegativeButton("取消", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				isHand = false;
				Message msg = new Message();
				msg.what = R.id.restart_preview;
				handler.sendMessageDelayed(msg, 3000);
			}

		});
		builder.create().show();
	}

	/**
	 *
	 */
	private void showHint(String content, int successCode) {
//		DialogFartory.showDialogSingle(this, content, mHandler, successCode);
	}
	
	
	 /** 检查设备是否支持摄像头  **/
    private boolean CheckCameraHardware(Context mContext)
    {
        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))
        { 
            // 摄像头存在 
            return true; 
        } else { 
            // 摄像头不存在 
            return false; 
        } 
    }

	@SuppressWarnings("deprecation")
	@Override
	protected void onResume() {
		super.onResume();
		/*if (!CheckCameraHardware(this)) {
			this.finish();
		}*/
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.capture_preview);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	public void handleDecode(String result) {
		if (!isHand) {
			inactivityTimer.onActivity();
			playBeepSoundAndVibrate();
			
			String realCode = AES.decrypt(result);
			if (!TextUtils.isEmpty(realCode)) {
				if (CommonMethod.getNetworkState(CaptureActivity.this) == 0) {
					CommonMethod.makeNotice(CaptureActivity.this, "先检查网络连接稍后重试");
					Message msg = new Message();
					msg.what = R.id.restart_preview;
					handler.sendMessageDelayed(msg, 3000);
					return;
				}
				QrCodeThd(realCode);
			} else {
				CommonMethod.makeNotice(this, "二维码格式不正确");
				// 连续扫描，不发送此消息扫描一次结束后就不能再次扫描
				// handler.sendEmptyMessage(R.id.restart_preview);
				Message msg = new Message();
				msg.what = R.id.restart_preview;
				handler.sendMessageDelayed(msg, 3000);
			}
		}

	}

	/**
	 * 截取扫描结果
	 *
	 * @param result
	 * @return
	 */
	private String parseQrcode(String result) {
		int indext = result.indexOf("qrId");
		String str = result.substring(indext + 4).replace("=", "");
		return str;
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);

			Point point = CameraManager.get().getCameraResolution();
			int width = point.y;
			int height = point.x;

			int x = mCropLayout.getLeft() * width / mContainer.getWidth();
			int y = mCropLayout.getTop() * height / mContainer.getHeight();

			int cropWidth = mCropLayout.getWidth() * width
					/ mContainer.getWidth();
			int cropHeight = mCropLayout.getHeight() * height
					/ mContainer.getHeight();

			setX(x);
			setY(y);
			setCropWidth(cropWidth);
			setCropHeight(cropHeight);
			// 设置是否需要截图
			setNeedCapture(true);

		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(CaptureActivity.this);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public Handler getHandler() {
		return handler;
	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	private final OnCompletionListener beepListener = new OnCompletionListener() {
		@Override
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	/**
	 * 24二维码扫描
	 * @param surfaceHolder
	 */
	private void QrCodeThd(String code){
		UserInfoBean userInfoBean = MyUserInfo.getInstance().getUserInfoBean();
		if (userInfoBean == null || (userInfoBean != null && TextUtils.isEmpty(userInfoBean.getSessionId()))) {
			mHandler.obtainMessage(HttpRequestHelper.GETDATA_FAIL, "请先登录").sendToTarget();
			return;
		}
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(this, HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair("code", code));
		HttpRequestHelper.executeHttpData(CaptureActivity.this, HttpRequestHelper.INVITE_CODE, params, mHandler, HttpRequestHelper.GETDATA_SUCCESS, HttpRequestHelper.GETDATA_FAIL);
	}
}